package com.zhihuishu.micro.course.openapi.app.impl.teacher;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.zhihuishu.micro.course.dto.LessonDto;
import com.zhihuishu.micro.course.log.LoggerCollectionEnum;
import com.zhihuishu.micro.course.log.LoggerTemplateUtil;
import com.zhihuishu.micro.course.model.Lesson;
import com.zhihuishu.micro.course.openapi.app.dto.LessonWebDto;
import com.zhihuishu.micro.course.openapi.app.teacher.LessonOpenService;
import com.zhihuishu.micro.course.service.ChapterService;
import com.zhihuishu.micro.course.service.LessonService;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.toolkit.helper.BeanHelper;

/**
 * 节的接口实现类
 * 
 * @author 嵇鹏
 * @descption:
 * 
 * 
 */
@Service("lessonOpenServiceForTeacherApp")
public class LessonOpenServiceImpl implements LessonOpenService {

    @Resource
    private LessonService lessonService;

    @Resource
    private ChapterService chapterService;
    
    protected Logger logger=LoggerFactory.getLogger(getClass());

    @Override
    public RemoteResult<Integer> saveLesson(LessonWebDto lessonWebDto, Long userId) {
        RemoteResult<Integer> remoteResult = new RemoteResult<Integer>();
        try {
            Assert.notNull(lessonWebDto, "lessonWebDto不能为空");
            Assert.notNull(userId, "用户id不能为空");
            LessonDto lessonDto = BeanHelper.transTo(lessonWebDto, LessonDto.class);
            lessonDto.setHaveChildren(0);// 默认没有子小节
            lessonDto.setHasKnowledegPoint(0);// 默认没有知识点
            lessonService.saveLessonForApp(lessonDto, userId);// 保存节
            lessonService.addLessonOnCourseRedis(lessonDto.getCourseId(), lessonDto.getId());// 保存课程-节的关系缓存
            //lessonService.touchLesson(lessonDto.getId());// 保存节的缓存
            
            chapterService.touchChapter(lessonDto.getChapterId());// 更新章的Hash缓存
            LoggerTemplateUtil.saveLogger(String.format("app保存节%d", lessonDto.getId()), userId,
                    LoggerCollectionEnum.lessonCollection, lessonDto.getCourseId());// 增加日志
            remoteResult.setResult(lessonDto.getId());// 返回新增的主键
        } catch (Exception e) {
            e.printStackTrace();
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
            logger.error("app保存小节失败,参数信息为{}",lessonWebDto,e);
            
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<LessonWebDto> queryLesssonById(Integer lessonId) {
        RemoteResult<LessonWebDto> remoteResult = new RemoteResult<LessonWebDto>();
        try {
            Assert.notNull(lessonId, "节id不能为空");
            LessonDto lessonDto = lessonService.get(lessonId);
            LessonWebDto lessonWebDto = BeanHelper.transTo(lessonDto, LessonWebDto.class);
            lessonWebDto.setVideoSec(lessonDto.getVideoSec()==null?0:lessonDto.getVideoSec().intValue());
            remoteResult.setResult(lessonWebDto);
            
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<Void> updateLesson(LessonWebDto lessonWebDto, Long courseId, Long userId) {
        RemoteResult<Void> remoteResult = new RemoteResult<Void>();
        try {
            Assert.notNull(lessonWebDto, "更新对象不能为空 ");
            Assert.notNull(lessonWebDto.getId(), "更新对象id不能为空");
            Assert.notNull(courseId, "课程id不能为空");
            Assert.notNull(userId, "用户id不能为空");
            LessonDto lessonDto = BeanHelper.transTo(lessonWebDto, LessonDto.class);
            lessonDto.setUpdateTime(new Date());
            lessonService.updateSelective(BeanHelper.transTo(lessonDto, Lesson.class));// 更新库
            lessonService.touchLesson(lessonDto.getId());// 更新缓存
            LoggerTemplateUtil.saveLogger(String.format("app更新节%d", lessonDto.getId()), userId,
                    LoggerCollectionEnum.lessonCollection, courseId);// 记录日志
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<Void> deleteLesson(Integer lessonId, Long courseId, Long userId) {
        RemoteResult<Void> remoteResult = new RemoteResult<Void>();
        try {
            Assert.notNull(lessonId, "节不能为空 ");
            Assert.notNull(courseId, "课程id不能为空");
            Assert.notNull(userId, "用户id不能为空");
            Lesson lesson = new Lesson();
            lesson.setId(lessonId);
            lesson = lessonService.queryById(lessonId);
            lesson.setUpdateTime(new Date());
            lesson.setIsDeleted(1);// 删除
            lessonService.updateSelective(lesson);
            lessonService.touchLesson(lessonId);// 更新节的hash缓存
            lessonService.removeLessonOnCourseRedis(courseId, lessonId);// 将节从 节--课程的关系缓存中移除
            List<Integer> lessons = lessonService.queryLessonsByChapterIdAndOrderNumber(
                    lesson.getChapterId(), lesson.getOrderNumber());
            lessonService.updateMinusOrderByChapterIdAndLessonOrderNumber(lesson.getChapterId(),
                    lesson.getOrderNumber());
            if (lessons != null && lessons.size() > 0) {
                for (Integer tempLessonId : lessons) {
                    lessonService.touchLesson(tempLessonId);
                }
            }
            LoggerTemplateUtil.saveLogger(String.format("app删除节%d ", lessonId), userId,
                    LoggerCollectionEnum.lessonCollection, courseId);// 记录日志

        } catch (Exception e) {
            remoteResult.setSuccess(false);
            remoteResult.setExceptionStack(e);
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<Void> updateLessonSort(LessonWebDto lessonWebDto, Long courseId, Long userId) {
        RemoteResult<Void> remoteResult = new RemoteResult<Void>();
        try {
            Assert.notNull(lessonWebDto, "排序对象不能为空");
            Assert.notNull(lessonWebDto.getId(), "id不能为空");
            Assert.notNull(lessonWebDto.getOriginRank(), "初始顺序不能为空");
            Assert.notNull(lessonWebDto.getTargetRank(), "排序后顺序不能为空");
            //Assert.notNull(lessonWebDto.getChapterId(), "章id不能为空");
            Assert.notNull(courseId, "课程id不能为空");
            Assert.notNull(userId, "用户id不能为空");
            int orginRank = lessonWebDto.getOriginRank();// 初始位置
            int targetRank = lessonWebDto.getTargetRank();// 排序后的位置
            Integer chapterId=lessonService.get(lessonWebDto.getId()).getChapterId();
            List<Integer> lessonIds = null;// 排序所影响的其他节
            if (orginRank > targetRank) {// 向前移动(4--->1)
                lessonIds = lessonService.queryLessonIdsContainSmallOrder(chapterId,
                        targetRank, orginRank);
            }
            if (orginRank < targetRank) {// 向后移动(1--->4)
                lessonIds = lessonService.queryLessonIdsContainBigOrder(chapterId,
                        targetRank, orginRank);
            }
            if (lessonIds != null && lessonIds.size() > 0) {
                for (Integer tempLessonId : lessonIds) {
                    lessonService.touchLesson(tempLessonId);// 更新缓存
                }
            }
            Lesson lesson = new Lesson();
            lesson.setId(lessonWebDto.getId());
            lesson.setUpdateTime(new Date());
            lesson.setOrderNumber(lessonWebDto.getTargetRank());
            lessonService.updateSelective(lesson);// 更新库
            lessonService.touchLesson(lesson.getId());// 更新缓存
            LoggerTemplateUtil.saveLogger(String.format("app更新节%d顺序由%d变为%d", lesson.getId(),orginRank,targetRank), userId,
                    LoggerCollectionEnum.lessonCollection, courseId);
            
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;

    }

}
